package com.qrxl.common.controller;

import com.qrxl.util.JGAssert;
import com.qrxl.common.JsonResult;
import com.qrxl.common.service.IFileStoreService;
import com.qrxl.common.vo.res.UploadRes;
import com.qrxl.enums.EnumUploadItem;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@Controller
@Api(tags = "通用模块接口")
public class FileController extends BaseController {

    @Autowired
    private IFileStoreService fileService;

    @PostMapping("/common/file/v1/upload")
    @ResponseBody
    @ApiOperation(value = "文件上传")
    @ApiImplicitParams({@ApiImplicitParam(name = "uploadFile", value = "媒体文件", required = true)})
    public JsonResult upload(@RequestParam MultipartFile uploadFile) throws Exception {
        JGAssert.notNull(uploadFile, "文件不能为空");
        uploadFile.getOriginalFilename();
        String path = fileService.uploadFile(EnumUploadItem.TEMP, uploadFile.getBytes(), uploadFile.getOriginalFilename());
        return JsonResult.genJsonResultByOk(UploadRes.builder().path(path).build());
    }

    @GetMapping("/{oss}/{upload}/{item}/{date}/{fileName}")
    @ResponseBody
    @ApiOperation(value = "文件访问")
    @ApiImplicitParams({@ApiImplicitParam(name = "path", value = "文件相对路径", required = true)})
    public void Visit(HttpServletResponse res,
                      @PathVariable String oss,
                      @PathVariable String upload,
                      @PathVariable String item,
                      @PathVariable String date,
                      @PathVariable String fileName
    ) throws Exception {
        if (!item.equalsIgnoreCase(EnumUploadItem.TEMP.getBaseDir())) {
//            getUserLoginInfo();
        }
        String path = "/" + oss + "/" + upload + "/" + item + "/" + date + "/" + fileName;
        JGAssert.hasText(path, "path不能为空");
        fileService.writeData(res, path);
    }
}
